package com.hanhai.material.wages.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.hanhai.material.common.constant.Constant;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.utils.redis.RedisUtil;
import com.hanhai.material.wages.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class AuthController {
    @Autowired
    Producer producer;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SysUserService sysUserService;

    @GetMapping("/captcha")
    public Result<?> getCaptcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        /*通过UUID生成随机key，并通过Kaptcha生成验证码图片*/
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64Encoder.encode(outputStream.toByteArray());
        /*将验证码的key保存到Redis*/
        redisUtil.hset(Constant.CAPTCHA_KEY, key, code, 60 * 3);
        return ResultTool.success(MapUtil.builder().put("token", key).put("captchaImg", base64Img).build());
    }
}
